package com.es.test.service.query;

import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import com.es.test.enums.LabelOperateEnum;
import com.es.test.query.Label;
import com.es.test.query.LabelListQuery;
import com.es.test.query.LabelQuery;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BuilderFactory {
    List<Query> builder(LabelListQuery labelListQuery) {

        List<FieldValue> fieldValues = new ArrayList<>();
        //根据关键字列表构件复合查询的值

        List<LabelQuery> labelQueries = labelListQuery.getLabelQueries();
        List<Query> queries = new ArrayList<>();

        Query.Builder queryBuilder = new Query.Builder();
        BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();

        for (LabelQuery labelQuery : labelQueries) {
            Label labelA = labelQuery.getLabelA();
            Label labelB = labelQuery.getLabelB();
            if (labelQuery.getLabelOperateEnum() == LabelOperateEnum.AND) {
                boolQueryBuilder.must(builder -> builder.term(t ->
                                t.field(labelA.getName()).value(String.valueOf(labelA.getValue()))))
                        .must(builder -> builder.term(t -> t.field(labelB.getName()).value(String.valueOf(labelB.getValue()))));
            } else if (labelQuery.getLabelOperateEnum() == LabelOperateEnum.OR) {
                boolQueryBuilder.should(builder -> builder.term(t ->
                                t.field(labelA.getName()).value(String.valueOf(labelA.getValue()))))
                        .should(builder -> builder.term(t -> t.field(labelB.getName()).value(String.valueOf(labelB.getValue()))));
            }
            boolQueryBuilder.minimumShouldMatch("1");

        }
        queryBuilder.bool(boolQueryBuilder.build());
        Query build = queryBuilder.build();

        return Arrays.asList(build);

    }

}
